package ui.fragments

import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.awt.SwingPanel
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.rememberDialogState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import models.PDFImageModel
import network.NetworkUtils.uploadImages
import org.apache.pdfbox.pdmodel.PDDocument
import ui.mini_fragments.PDFImageView
import ui.widget.DatePicker
import ui.widget.PDFImage
import ui.widget.ProgressCircle
import utils.PDFUtils
import java.awt.datatransfer.DataFlavor
import java.awt.dnd.DnDConstants
import java.awt.dnd.DropTarget
import java.awt.dnd.DropTargetAdapter
import java.awt.dnd.DropTargetDropEvent
import java.awt.image.BufferedImage
import java.io.File
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import javax.swing.BorderFactory
import javax.swing.ImageIcon
import javax.swing.JLabel

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun MainFragment() {
    var customer by remember { mutableStateOf("") }
    //var device by remember { mutableStateOf("") }
    var serialNumber by remember { mutableStateOf("") }
    var date by remember { mutableStateOf(LocalDate.now()) }
    val pages = remember { mutableStateListOf<PDFImageModel>() }
    var showDetailImage by remember { mutableStateOf(false) }
    val imageCanvas = PDFImage(BufferedImage(100, 100, BufferedImage.TYPE_4BYTE_ABGR))

    var showDialog by remember { mutableStateOf(false) }

    var successCount by remember { mutableStateOf(0) }
    var failedCount by remember { mutableStateOf(0) }
    var currentIndex by remember { mutableStateOf(1) }

    //日期选择器
    val dialogState = rememberDialogState()
    //Dialog()
    //var currentPage by remember { mutableStateOf<BufferedImage>(BufferedImage(100,100,BufferedImage.TYPE_4BYTE_ABGR)) }
    Row(modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.SpaceBetween) {
        Box(modifier = Modifier.fillMaxWidth(0.8f).fillMaxHeight()) {
            DatePicker { println(it.format(DateTimeFormatter.ISO_DATE)) }
            /*if (showDialog) {
                Box(modifier = Modifier.fillMaxSize())
            }
            else {
                if (showDetailImage) {
                    SwingPanel(background = Color.White, modifier = Modifier.fillMaxSize().padding(3.dp), factory = {
                        imageCanvas
                    })
                } else {
                    SwingPanel(background = Color.White, modifier = Modifier.fillMaxSize().padding(3.dp), factory = {
                        JLabel(ImageIcon("src/main/resources/drawable/upload_bitmap.png")).apply {
                            //this.background = java.awt.Color(255,255,255,0)
                            border = BorderFactory.createLineBorder(java.awt.Color.GRAY, 3, true)
                            toolTipText = "拖入PDF文件进行上传"
                            DropTarget(this, DnDConstants.ACTION_COPY, object : DropTargetAdapter() {
                                override fun drop(dtde: DropTargetDropEvent?) {
                                    dtde?.acceptDrop(DnDConstants.ACTION_COPY)
                                    val transferable = dtde?.transferable
                                    val flavors = transferable?.transferDataFlavors
                                    flavors?.also { flavors1 ->
                                        try {
                                            for (f in flavors1) {
                                                if (f.equals(DataFlavor.javaFileListFlavor)) {
                                                    for (file in transferable.getTransferData(f) as List<*>) {
                                                        println("开始加载pdf文件")
                                                        val doc = PDDocument.load(file as File)
                                                        for (page in doc.pages) {
                                                            val images = PDFUtils.getImageFromResource(page.resources)
                                                            pages.addAll(images)
                                                        }
                                                        println("关闭pdf文件")
                                                        doc.close()
                                                    }
//                                            val fis = transferable.getTransferData(f) as InputStream
//                                            Files.copy(fis, Paths.get("g://copy.pdf"))
                                                }
                                            }
                                        } catch (e: Exception) {
                                            e.printStackTrace()
                                        }
                                    }
                                }
                            })
                        }
                    })
                }
            }*/
        }


        val scope = rememberCoroutineScope()
        Column(modifier = Modifier.fillMaxWidth().fillMaxHeight()) {
            var expanded by remember { mutableStateOf(false) }
            var deviceExpand by remember { mutableStateOf(false) }
            Column(modifier = Modifier.fillMaxWidth()) {
                OutlinedTextField(
                    value = customer,
                    onValueChange = { customer = it },
                    label = { Text("输入客户名称") },
                    modifier = Modifier.fillMaxWidth()
                        .padding(3.dp)
                )
                /*DropdownMenu(
                    expanded = expanded,
                    onDismissRequest = { expanded = false }
                ) {
                    factories.forEach {
                        DropdownMenuItem(onClick = { expanded = false;factory = it }) {
                            Text(it)
                        }
                    }
                }*/
                OutlinedTextField(
                    value = serialNumber,
                    onValueChange = { serialNumber = it },
                    label = { Text("输入报告编号") },
                    modifier = Modifier.fillMaxWidth()
                        .padding(3.dp)
                )
                OutlinedTextField(
                    value = serialNumber,
                    onValueChange = { serialNumber = it },
                    label = { Text("输入报告日期") },
                    modifier = Modifier.fillMaxWidth()
                        .padding(3.dp)
                        .onFocusChanged {
                            if (it.hasFocus)
                            {

                            }
                        }
                )
                /*DropdownMenu(
                    expanded = deviceExpand,
                    onDismissRequest = { deviceExpand = false }
                ) {
                    devices.forEach {
                        DropdownMenuItem(onClick = { deviceExpand = false;device = it }) {
                            Text(it)
                        }
                    }
                }*/
                LazyColumn(modifier = Modifier.fillMaxWidth().weight(1f, fill = true).padding(2.dp)) {
                    items(pages)
                    {
                        PDFImageView(it) { image ->
                            imageCanvas.image = image
                            imageCanvas.repaint()
                            showDetailImage = true
                        }
                    }
                }
                Button(onClick = {
                    pages.clear();showDetailImage = false;System.gc();successCount = 0;failedCount = 0;
                }, modifier = Modifier.fillMaxWidth().padding(2.dp)) {
                    Text("清空")
                }
                Button(onClick = {
                    if (pages.isNotEmpty() && customer.isNotEmpty() && serialNumber.isNotEmpty()) {
                        scope.launch {
                            showDialog = true
                            pages.forEach {
                                withContext(Dispatchers.IO) {
                                    val result = uploadImages(it.image, "${customer}_${date.format(DateTimeFormatter.ISO_DATE)}_${currentIndex}.png")
                                    if (result) {
                                        successCount++
                                    } else {
                                        failedCount++
                                    }
                                    currentIndex++
                                }
                            }

                        }
                    }
                }, modifier = Modifier.fillMaxWidth().padding(2.dp)) {
                    Text("开始上传")
                }

            }

        }

    }

    if (showDialog) {
        AlertDialog(onDismissRequest = {
            //showDialog = false
        },
            title = {
                Text(text = "")
            },
            text = {
                Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth()) {
                    ProgressCircle(
                        currentIndex.toFloat() / pages.size,
                        modifier = Modifier.size(150.dp),
                        color = if (currentIndex > pages.size) Color.Green else Color(0xff4672C4)
                    )
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text("正在上传第$currentIndex 张图片")
                        Text("成功上传$successCount 张图片")
                        Text("上传失败$failedCount 张图片")
                    }
                }


            },
            confirmButton = {
                TextButton(
                    onClick = {
                        showDialog = false
                    }
                ) {
                    Text("确定")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        showDialog = false
                    }
                ) {
                    Text("取消")
                }
            })
    }
}

@Preview
@Composable
fun PreviewMainFragment() {
    MainFragment()
}

val factories = listOf("漕泾热电", "闵行燃机")
val devices = listOf("发电机", "变压器", "开关柜", "gis", "避雷器", "接地装置")